import { Command } from 'commander'
import chalk from 'chalk'
import inquirer from 'inquirer'
import { writeFileSync, existsSync, mkdirSync } from 'fs'
import { join } from 'path'

export const initCommand = new Command('init')
  .description('Initialize a new project')
  .option('-n, --name <name>', 'project name')
  .option('-t, --template <template>', 'project template', 'basic')
  .action(async options => {
    try {
      console.log(chalk.blue('🚀 Initializing new project...'))

      let projectName = options.name
      let template = options.template

      // If no name provided, ask for it
      if (!projectName) {
        const answers = await inquirer.prompt([
          {
            type: 'input',
            name: 'name',
            message: 'What is your project name?',
            default: 'my-project',
            validate: (input: string) => {
              if (!input.trim()) {
                return 'Project name is required'
              }
              return true
            },
          },
        ])
        projectName = answers.name
      }

      // If no template provided, ask for it
      if (!template || template === 'basic') {
        const answers = await inquirer.prompt([
          {
            type: 'list',
            name: 'template',
            message: 'Choose a template:',
            choices: [
              { name: 'Basic TypeScript Project', value: 'basic' },
              { name: 'Express API', value: 'express' },
              { name: 'React App', value: 'react' },
            ],
            default: 'basic',
          },
        ])
        template = answers.template
      }

      // Create project directory
      const projectPath = join(process.cwd(), projectName)

      if (existsSync(projectPath)) {
        console.error(chalk.red(`❌ Directory ${projectName} already exists!`))
        process.exit(1)
      }

      mkdirSync(projectPath, { recursive: true })

      // Create basic project structure
      const packageJson = {
        name: projectName,
        version: '1.0.0',
        description: `A ${template} project created with my-cli`,
        main: 'dist/index.js',
        type: 'module',
        scripts: {
          dev: 'echo "Development server not configured"',
          build: 'echo "Build script not configured"',
          start: 'echo "Start script not configured"',
        },
        keywords: [],
        author: '',
        license: 'MIT',
      }

      // Write package.json
      writeFileSync(
        join(projectPath, 'package.json'),
        JSON.stringify(packageJson, null, 2)
      )

      // Create basic README
      const readme = `# ${projectName}

A ${template} project created with my-cli.

## Getting Started

\`\`\`bash
cd ${projectName}
npm install
npm run dev
\`\`\`

## Available Scripts

- \`npm run dev\` - Start development server
- \`npm run build\` - Build for production
- \`npm run start\` - Start production server

## License

MIT
`

      writeFileSync(join(projectPath, 'README.md'), readme)

      console.log(chalk.green('✅ Project initialized successfully!'))
      console.log(chalk.gray(`\nNext steps:`))
      console.log(chalk.gray(`  cd ${projectName}`))
      console.log(chalk.gray(`  npm install`))
      console.log(chalk.gray(`  npm run dev`))
    } catch (error) {
      console.error(chalk.red('❌ Error initializing project:'), error)
      process.exit(1)
    }
  })
